<template>
	<view class="content">
		<button type="default" @click="PrintCode">打印</button>
	</view>
</template>

<script>
		import tsc from "@/utils/print/tsc.js"
	export default {
		data() {
			return {
				title: 'Hello',
				connId: '',
				currDev: "",
				devices:[]
			}
		},
		onLoad() {

		},
		methods: {
			PrintCode() {
				const errorMsg = {
					10000: '未初始化蓝牙模块',
					10001: '蓝牙未打开',
					10002: '没有找到指定设备',
					10003: '连接失败',
					10004: '没有找到指定服务',
					10005: '没有找到指定特征值',
					10006: '当前连接已断开',
					10007: '当前特征值不支持此操作',
					10008: '系统上报异常',
					10009: '系统版本低于 4.3 不支持BLE'
				}
				var that=this;
				// 初始化蓝牙模块
				uni.openBluetoothAdapter({
					// 蓝牙初始化成功
					success(res) {
						console.log(res)
						that.findDevice()
					},
					// 蓝牙初始化失败
					fail(error) {
						uni.showModal({
							title: '提示',
							// 策略模式
							content: errorMsg[error.code],
							showCancel: false
						})
					}
				})
			},
			findDevice() {
				var that = this;
				console.log("监听寻找到新设备的事件---------------")
				//监听寻找到新设备的事件
				uni.startBluetoothDevicesDiscovery({
					success(res) {
						// console.log(res)
						uni.onBluetoothDeviceFound(function(devices) {
							// 打印搜索的蓝牙设别
							console.log(devices.devices[0].name)
							const {
								name,
								deviceId
							} = devices.devices[0];
							//  搜索出来的名称是否为打印机的蓝牙名称  GP-M322-A68C_BLE 修改这里就行了改成自己的
							if (name == "GP-M322-A68C_BLE") {
								that.devices.push({
									name: name,
									deviceId: deviceId,
									services: []
								})
								that.onlink(that.devices[0])
								console.log(devices.devices[0])
							}
						})
					}
				})
			},
			onlink(item) {
				var that = this;
				const {
					deviceId
				} = item;
				uni.createBLEConnection({
					deviceId: deviceId,
					complete(res) {
						if (res.errMsg != "createBLEConnection:ok") return
						//连接设备时，需断开本机连接设备
						that.connId = deviceId;
						that.currDev = item;
						setTimeout(() => {
							//获取蓝牙设备所有服务(service)
							that.getBLEServices(deviceId)
						}, 2000)
						// that.onPrint()
					},
				})
				//连接成功 关闭搜索
				uni.stopBluetoothDevicesDiscovery()
			},
			getBLEServices(deviceId) {
				var that = this;
				uni.getBLEDeviceServices({
					deviceId: deviceId,
					complete(res) {
						// console.log(res)
						const {
							services
						} = res;
						services.forEach(item => {
							const {
								uuid
							} = item;
							uni.getBLEDeviceCharacteristics({
								// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
								deviceId: deviceId,
								serviceId: uuid,
								success(res) {
									// console.log(res)
									const {
										characteristics
									} = res;
									for (let block of characteristics) {
										if (!block.properties.write) return
										for (let index in that.devices) {
											if (that.devices[0].deviceId == deviceId) {
												that.devices[0].services.push({
													serviceId: uuid,
													characteristicId: block.uuid,
												})
												break
											}
										}
									}
									that.onPrint()
								}
							})
						})
					}
				})
			},
			onPrint() {

				const {
					deviceId
				} = this.currDev;
				const {
					serviceId,
					characteristicId
				} = this.devices[0].services[0];
				uni.showToast({
					icon: 'none',
					title: "正在打印请稍等，如果没有打印请重新点击打印",
					duration: 3000
				});
				var command = tsc.jpPrinter.createNew();
				console.log(command)
				command.setSize(250, 200)
				command.setGap(2)
				command.setCls()
				command.setQR(200, 50, "L", 5, "A", "977767937@qq.com")
				command.setText(50, 90, "TSS24.BF2", 1, 1, "打印测试")
				command.setPagePrint()
				this.senBlData(deviceId, serviceId, characteristicId, command.getData())
			},
			// 格式化数据
			senBlData(deviceId, serviceId, characteristicId, uint8Array) {
				var that = this;
				console.log('************deviceId = [' + deviceId + ']  serviceId = [' + serviceId +
					'] characteristics=[' + characteristicId + "]")
				var uint8Buf = Array.from(uint8Array);

				function split_array(datas, size) {
					var result = {};
					var j = 0
					for (var i = 0; i < datas.length; i += size) {
						result[j] = datas.slice(i, i + size)
						j++
					}
					console.log(result)
					return result
				}
				var sendloop = split_array(uint8Buf, 20);
				// console.log(sendloop.length)
				function realWriteData(sendloop, i) {
					var data = sendloop[i]
					if (typeof(data) == "undefined") {
						return
					}
					console.log("第【" + i + "】次写数据" + data)
					var buffer = new ArrayBuffer(data.length)
					var dataView = new DataView(buffer)
					for (var j = 0; j < data.length; j++) {
						dataView.setUint8(j, data[j]);
					}
					uni.writeBLECharacteristicValue({
						deviceId,
						serviceId,
						characteristicId,
						value: buffer,
						success(res) {
							realWriteData(sendloop, i + 1);
						}
					})
				}
				var i = 0;
				realWriteData(sendloop, i);
				setTimeout(() => {
					that.DisconnectBluetooth(deviceId)
				}, 10000)
			},
			// 断开蓝牙
			DisconnectBluetooth(deviceId) {
				uni.closeBLEConnection({
					deviceId,
					success(res) {
						console.log(res)
					}
				})
			},
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
